<?php

namespace app\command;

use app\common\command\BaseCommand;
use app\home\model\Member;
use app\home\model\Score;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use libs\Log;
use think\db\Where;
use think\facade\Debug;
use think\model\Collection;

class Migration extends BaseCommand
{
    protected function configure()
    {
        $this->setName('Migration')
            ->addOption('migration', 'm', Option::VALUE_NONE, 'this is a value_none option')
            ->addOption('required', null, Option::VALUE_REQUIRED, 'this is a value_required option')
            ->addOption('optional', null, Option::VALUE_OPTIONAL, 'this is a value_optional option')
            // 必选参数一定要在可选参数之前
            // ->addArgument('required', Argument::REQUIRED, "argument::required")
            ->addArgument('func', Argument::OPTIONAL, "argument::optional", 'test')
            ->setDescription('this is a description');
    }

    protected function execute(Input $input, Output $output)
    {
        //获取本周用户的活跃值
        //本周时间戳
        $time1 = mktime(0, 0, 0, date('m'), date('d') - date('N') + 1, date('y'));
        $time2 = mktime(23, 59, 59, date('m'), date('d') - date('N') + 7, date('Y'));
        $score = new Score();
        $data = $score->where('status', 0)->whereBetweenTime('create_time', $time1, $time2)->field('id,member_id,task_id,status,create_time,sum(score) as total_score')->group('member_id')->select()->toArray();
        $success_count = 0;
        foreach ($data as $v) {
            if ($v['total_score'] > 300) {
                $diff_score = $v['total_score'] - 300;
                //获取用户当前积分
                $integral = Member::where('member_id', $v['member_id'])->value('integral');
                $now_score = $integral + $diff_score;
                $update = [
                    'integral' => $now_score,
                ];
                $res = Member::update($update, ['member_id' => $v['member_id']]);
                if ($res) {
                    //执行成功活跃值记录status更改为1，过期
                    Score::update(['status' => 1], ['member_id' => $v['member_id']]);
                    $success_count += 1;
                }
            }
        }
        echo "脚本执行完毕,成功" . $success_count . "个";
    }
}
